﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FirstDemo.Attr
{
    public class HandleExceptionAttribute : ExceptionFilterAttribute
    {
        private readonly string _message;

        public HandleExceptionAttribute()
        {
        }

        public HandleExceptionAttribute(string message)
        {
            _message = message;
        }

        public override Task OnExceptionAsync(ExceptionContext context)
        {
            //获取异常信息，入库保存
            var exception = context.Exception;
            var controllerName = context.RouteData.Values["controller"].ToString();
            var actionName = context.RouteData.Values["action"].ToString();
            var msg = $"出错位置:{controllerName}/{actionName}-----出错时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss:fff}-----出错消息:{exception.Message}";
            Console.WriteLine(msg);
            context.Result = new JsonResult(msg);
            context.ExceptionHandled = true;
            return base.OnExceptionAsync(context);
        }

        public override void OnException(ExceptionContext context)
        {
            
        }
    }
}
